package my.sample.quartz.datamap;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.joda.time.LocalTime;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

public class SimpleJob implements Job {

//		Logger log = LoggerFactory.getLogger(SimpleJob.class);
	private static Logger log = null;

	public SimpleJob() {
		log = LoggerFactory.getLogger(SimpleJob.class);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			
			log.info("Execute: Details : "
				+ " at : " + new Date()	
				+ " : Previous Fire time : " + context.getPreviousFireTime()
				+ " : Next Fire time : " + context.getNextFireTime()
				+ " : Scheduled Fire time : " + context.getScheduledFireTime()
				+ " : Fire Instance ID : " + context.getFireInstanceId()
				+ " : Job Run Time : " + context.getJobRunTime()
				+ " : Refire Count : " + context.getRefireCount()
				+ " : Fire Time : " + context.getFireTime()
					);
			
			String fileName = context.getTrigger().getKey().getName();
			File file = new File(fileName + ".txt");

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// true = append file
			FileWriter fileWritter = new FileWriter(file.getName(), true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
			bufferWritter.write(new Date().toString()
					+ "data map value for one "
					+ context.getJobDetail().getJobDataMap().getString("one")
					+ "other = "
					+ context.getJobDetail().getJobDataMap().getString("other")
					+ "\n");
			bufferWritter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
